import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QVBoxLayout
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib.patches import Circle, Rectangle

class MyMainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Matplotlib Animation in PyQt')
        self.setGeometry(100, 100, 800, 600)

        # 创建主窗口部件
        main_widget = QWidget(self)
        self.setCentralWidget(main_widget)

        # 创建布局
        layout = QVBoxLayout(main_widget)

        # 创建 matplotlib 图形容器
        self.fig, self.ax = plt.subplots()
        self.ax.set_xlim(-60, 60)
        self.ax.set_ylim(-60, 60)
        self.ax.set_aspect('equal')

        # 创建初始图形对象
        self.circle = Circle((0, 0), radius=0, fc='blue', alpha=0.5)
        self.rectangle = Rectangle((-50, -50), width=0, height=0, fc='red', alpha=0.5)
        self.ax.add_patch(self.circle)
        self.ax.add_patch(self.rectangle)

        # 创建标签
        self.label_obj = self.ax.annotate("", xy=(0, 0), fontsize=12, ha='center')
        self.label_obj.set_position((0.5, 0.95))  # 设置标签位置
        self.label_obj.set_text("I love you everyday.")

        # 创建 matplotlib 画布并添加到布局
        self.canvas = FigureCanvas(self.fig)
        layout.addWidget(self.canvas)

        # 设置标签与窗口大小一致
        self.ax.set_position([0, 0, 1, 1])

        # 设置帧数和总时长
        self.frames = 100
        self.ani_duration = 3  # 动画时长为3秒

        # 创建动画
        self.ani = FuncAnimation(self.fig, self.update, frames=self.frames,
                                 interval=(self.ani_duration * 1000) / self.frames, blit=True)

    def update(self, frame):
        t = frame / self.frames  # 计算当前时间占总时长的比例
        if t <= 0.5:
            # 绘制蓝色圆形
            self.circle.set_radius(50 * t)
            self.circle.set_facecolor('blue')
            self.label_obj.set_text("I love you everyday. (Circle)")
        else:
            # 绘制红色方块
            self.rectangle.set_width(100 * (t - 0.5))
            self.rectangle.set_height(100 * (t - 0.5))
            self.rectangle.set_xy((-50 * (t - 0.5), -50 * (t - 0.5)))
            self.rectangle.set_facecolor('red')
            self.label_obj.set_text("I love you everyday. (Rectangle)")

        return self.circle, self.rectangle, self.label_obj

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main_window = MyMainWindow()
    main_window.show()
    sys.exit(app.exec_())
